package com.wencai.test;

import org.jetbrains.annotations.NotNull;
import com.wencai.util.IOUtils;

import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author wangpan
 * @date 2023/6/14
 */
public class TwoMonthSelectStock {
    private static String dir = "D:\\Users\\Administrator\\Desktop\\记录\\概念\\";
    private static String outPath = "D:\\Users\\Administrator\\Desktop\\记录\\近两月有异动的代码.txt";

    private static Pattern p = Pattern.compile("([^0-9_ \t]+)_(sh\\.\\d+|sz\\.\\d+) (\\d+(\\.\\d+)?)");
    private static Pattern p0 = Pattern.compile("[^0-9_ \t]+_(\\d+\\.TI)\\([.\\d-]");


    public static void main(String[] args) throws IOException {
        String currentMonth = getString(LocalDate.now());
        String lastMonth = getString(LocalDate.now().plusMonths(-1));
        File f = new File(dir);
        List<String> list = Arrays.asList(f.list()).stream().filter(str -> str.startsWith(currentMonth) || str.startsWith(lastMonth)).collect(Collectors.toList());
        Collections.sort(list);
        Set<String> set0 = new LinkedHashSet<>();
        Set<String> set = new LinkedHashSet<>();
        for (String str : list) {
            if (str.startsWith(currentMonth) || str.startsWith(lastMonth)) {
                List<String> lines = IOUtils.readFromFile(dir + str);
//                set.add(str);
                for (String line : lines) {
                    Matcher m0 = p0.matcher(line);
                    m0.find();
//                    set0.add(m0.group(1));
                    Matcher m = p.matcher(line);
                    while (m.find()) {
                        Double d = Double.valueOf(m.group(3));
                        if (d > 7) {
                            System.out.print(str.replace(".txt","")+"--");
                            System.out.print(m.group(1)+"--");
                            System.out.print(m.group(3));
                            System.out.println();
                            set.add(m.group(2));
                        }
                    }
                }
            }
        }
        System.out.println(set0);
        System.out.println(set);
        StringBuilder builder = new StringBuilder();
        for (String str : set0) {
            builder.append(str).append(System.lineSeparator());
        }
        for (String str : set) {
            builder.append(str).append(System.lineSeparator());
        }
        IOUtils.writeFile(outPath, builder.toString());
    }

    @NotNull
    private static String getString(LocalDate localDate) {
        Instant instant = localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
        return new SimpleDateFormat("YYYYMM").format(Date.from(instant));
    }
}
